package com.huan.dao;

import java.sql.*;
import java.util.Calendar;

/**
 * 作者： huan~
 *
 * @Date 2022-04-12 20:42
 * @Description
 */
public class CategoryDao extends BaseDao {
    private Connection conn;
    //    private Statement stmt;
    private PreparedStatement pstmt; // 预防sql注入
    private ResultSet rs;


    /**
     * 查询数据库 - news_category
     *
     * @param name
     */
    public void getCategoryList(String name)
    {
        String sql = "select * from new.news_category where name like ?";
        rs = executeSQL(sql, new Object[]{name});
        // 4.获取查询结果
        try {
            while (rs != null && rs.next()) {
                int id = rs.getInt("id");
                String category_name = rs.getString("name");
                Timestamp createdate = rs.getTimestamp("createdate");
                System.out.println("Id: " + id + ", 分类名称: " + category_name + ", 创建日期: " + createdate);
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            closeResource();
        }
    }


    /**
     * 修改类别名称 news_category
     *
     * @param name
     * @param id
     * @return
     */
    public void updateCategory(String name, int id)
    {
        String sql = "update new.news_category set name=? where id=?";
        int i = executeUpdate(sql, new Object[]{name, id});
        if (i > 0) {
            System.out.println("id: " + id + "修改成功");
            new UserDao().getUserList(name);
        } else {
            System.out.println("id: " + id + "修改失败，请重新修改");
        }
    }

    /**
     * 添加一个类别
     *
     * @param name
     */
    public void addCategory(String name)
    {
        String sql = "insert into new.news_category (name,createdate) values (?,?)";
        int i = executeUpdate(sql, new Object[]{name, new Timestamp(Calendar.getInstance().getTimeInMillis())});
        if (i > 0) {
            System.out.println("类别: " + name + "添加成功");
            new CategoryDao().getCategoryList(name);
        } else {
            System.out.println("类别: " + name + "添加失败，请重新添加");
        }
    }

    /**
     * 根据ID删除一个类别
     *
     * @param id
     * @return
     */
    public void deleteCategory(int id)
    {
        String sql = "delete from new.news_category where id=?";
        int i = executeUpdate(sql, new Object[]{id});
        if (i > 0) {
            System.out.println("id: " + id + "删除成功");
        } else {
            System.out.println("id: " + id + "删除失败，请重新删除");
        }
    }

    public static void main(String[] args)
    {
        /* 添加数据
        new CategoryDao().addCategory("教育");*/
        /* 修改
        new CategoryDao().updateCategory("科技", 7);*/
        /* 查询
        new CategoryDao().getCategoryList("科技");*/
        /* 删除*/
        new CategoryDao().deleteCategory(7);
    }
}